package com.farm.authority.service.impl;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.farm.authority.domain.Action;
import com.farm.authority.domain.AuthMenuImpl;
import com.farm.authority.domain.Organization;
import com.farm.authority.domain.Post;
import com.farm.authority.domain.User;
import com.farm.authority.domain.Userpost;
import com.farm.authority.dao.OrganizationDaoInter;
import com.farm.authority.dao.PostDaoInter;
import com.farm.authority.dao.UserDaoInter;
import com.farm.authority.dao.UserpostDaoInter;
import com.farm.authority.service.UserServiceInter;
import com.farm.core.FarmService;
import com.farm.core.auth.domain.LoginUser;
import com.farm.core.auth.domain.WebMenu;
import com.farm.core.auth.util.AuthenticateInter;
import com.farm.core.auth.util.AuthenticateProvider;
import com.farm.core.sql.query.DBRule;
import com.farm.core.sql.query.DataQuery;
import com.farm.core.time.TimeTool;

/* *
 *功能：用户服务层实现类
 *详细：
 *
 *版本：v0.1
 *作者：王东
 *日期：20141119144919
 *说明：
 */
public class UserServiceImpl implements UserServiceInter {
	private UserDaoInter userDao;
	private UserpostDaoInter userpostDao;
	private PostDaoInter postDao;
	private OrganizationDaoInter organizationDao;
	private AuthenticateInter authUtil = AuthenticateProvider.getInstance();
	// private static final Logger log =
	// Logger.getLogger(UserServiceImpl.class);
	private static final FarmService farmService = FarmService.getInstance();

	@Override
	public User insertUserEntity(User entity, LoginUser user) {
		entity.setCuser(user.getId());
		entity.setCtime(TimeTool.getTimeDate14());
		entity.setMuser(user.getId());
		entity.setUtime(TimeTool.getTimeDate14());
		if (validateIsRepeatLoginName(entity.getLoginname(), null)) {
			throw new RuntimeException("登录名已经存在!");
		}
		entity.setPassword(authUtil.encodeLoginPasswordOnMd5(farmService
				.getParameterService().getParameter("config.default.password"),
				entity.getLoginname()));
		return userDao.insertEntity(entity);
	}

	@Override
	public User editUserEntity(User entity, LoginUser user) {
		User entity2 = userDao.getEntity(entity.getId());
		if (validateIsRepeatLoginName(entity.getLoginname(), entity2.getId())) {
			throw new RuntimeException("登录名已经存在!");
		}
		if (entity2.getState().equals("2")) {
			throw new RuntimeException("该用户已被删除，无法修改");
		}
		entity2.setMuser(user.getId());
		entity2.setUtime(TimeTool.getTimeDate14());
		entity2.setLoginname(entity.getLoginname());
		entity2.setState(entity.getState());
		entity2.setType(entity.getType());
		entity2.setComments(entity.getComments());
		entity2.setName(entity.getName());
		userDao.editEntity(entity2);
		return entity2;
	}

	@Override
	public boolean validateIsRepeatLoginName(String loginname, String userId) {
		List<User> list = null;
		if (userId == null || userId.trim().equals("")) {
			list = userDao.findUserByLoginName(loginname.trim());
		} else {
			list = userDao.findUserByLoginName(loginname.trim(), userId);
		}
		return list.size() > 0;
	}

	@Override
	public void deleteUserEntity(String id, LoginUser user) {
		User entity2 = userDao.getEntity(id);
		entity2.setMuser(user.getId());
		entity2.setUtime(TimeTool.getTimeDate14());
		entity2.setState("2");
		entity2.setLoginname(entity2.getId());
		userDao.editEntity(entity2);
	}

	@Override
	public User getUserEntity(String id) {
		if (id == null) {
			return null;
		}
		return userDao.getEntity(id);
	}

	@Override
	public DataQuery createUserSimpleQuery(DataQuery query) {
		DataQuery dbQuery = DataQuery
				.init(
						query,
						"ALONE_AUTH_USER a LEFT JOIN  (SELECT b.USERID AS userid,c.ORGANIZATIONID AS ORGANIZATIONID FROM ALONE_AUTH_USERORGPOST b LEFT JOIN ALONE_AUTH_POST c ON b.POSTID=c.ID  WHERE c.TYPE='1')  a1 ON a1.userid=a.ID LEFT JOIN alone_auth_organization a3 ON a3.ID=a1.ORGANIZATIONID ",
						"a.ID as ID,a.LOGINTIME as LOGINTIME,a.LOGINNAME as LOGINNAME,a.STATE as STATE,a.TYPE as TYPE,a.COMMENTS as COMMENTS,a.NAME as NAME,a3.name as ORGNAME");
		return dbQuery;
	}

	// ----------------------------------------------------------------------------------
	public UserDaoInter getUserDao() {
		return userDao;
	}

	public UserpostDaoInter getUserpostDao() {
		return userpostDao;
	}

	public PostDaoInter getPostDao() {
		return postDao;
	}

	public void setPostDao(PostDaoInter postDao) {
		this.postDao = postDao;
	}

	public OrganizationDaoInter getOrganizationDao() {
		return organizationDao;
	}

	public void setOrganizationDao(OrganizationDaoInter organizationDao) {
		this.organizationDao = organizationDao;
	}

	public void setUserpostDao(UserpostDaoInter userpostDao) {
		this.userpostDao = userpostDao;
	}

	public void setUserDao(UserDaoInter dao) {
		this.userDao = dao;
	}

	@Override
	public void initDefaultPassWord(String userid, LoginUser currentUser) {
		User entity2 = userDao.getEntity(userid);
		entity2.setMuser(currentUser.getId());
		entity2.setUtime(TimeTool.getTimeDate14());
		entity2.setPassword(authUtil.encodeLoginPasswordOnMd5(farmService
				.getParameterService().getParameter("config.default.password"),
				entity2.getLoginname()));
		userDao.editEntity(entity2);
	}

	@Override
	public User getUserByLoginName(String loginName) {
		List<User> users = userDao.findUserByLoginName(loginName);
		if (users.size() <= 0) {
			return null;
		}
		if (users.size() > 1) {
			throw new RuntimeException("该登录名返回了多个用户！");
		}
		return users.get(0);
	}

	@Override
	public void setLoginTime(String userId) {
		User entity2 = userDao.getEntity(userId);
		entity2.setLogintime(TimeTool.getTimeDate14());
		userDao.editEntity(entity2);
	}

	@Override
	public DataQuery createUserPostQuery(DataQuery query) {
		DataQuery dbQuery = DataQuery
				.init(
						query,
						"alone_auth_post a LEFT JOIN alone_auth_userorgpost b ON a.ID=b.POSTID LEFT JOIN alone_auth_user c ON b.USERID=c.ID ",
						"c.id AS USERID,c.logintime as logintime,c.NAME AS username,c.STATE AS userstate,a.NAME AS postname,a.id as POSTID,a.TYPE AS TYPE  ");
		dbQuery.addSqlRule("and c.id is not null");
		return dbQuery;
	}

	@Override
	public List<Action> getUserActions(String userId) {
		DataQuery dbQuery = DataQuery
				.getInstance(
						1,
						"d.id,d.AUTHKEY,d.NAME,d.COMMENTS,d.STATE,d.CHECKIS,d.LOGINIS",
						"alone_auth_userorgpost a LEFT JOIN alone_auth_postaction b ON a.POSTID =b.POSTID LEFT JOIN alone_auth_actiontree c ON b.MENUID=c.ID LEFT JOIN alone_auth_action d ON d.ID=c.ACTIONID");
		dbQuery.addRule(new DBRule("d.STATE", "1", "="));
		dbQuery.addRule(new DBRule("a.USERID", userId, "="));
		dbQuery.setDistinct(true);
		dbQuery.setPagesize(5000);
		List<Action> list = new ArrayList<Action>();
		try {
			for (Map<String, Object> node : dbQuery.search().getResultList()) {
				Action action = new Action();
				action.setAuthkey(node.get("D_AUTHKEY") != null ? node.get(
						"D_AUTHKEY").toString() : null);
				action.setId(node.get("D_ID") != null ? node.get("D_ID")
						.toString() : null);
				action.setName(node.get("D_NAME") != null ? node.get("D_NAME")
						.toString() : null);
				action.setComments(node.get("D_COMMENTS") != null ? node.get(
						"D_COMMENTS").toString() : null);
				action.setState(node.get("D_STATE") != null ? node.get(
						"D_STATE").toString() : null);
				action.setCheckis(node.get("D_CHECKIS") != null ? node.get(
						"D_CHECKIS").toString() : null);
				action.setLoginis(node.get("D_LOGINIS") != null ? node.get(
						"D_LOGINIS").toString() : null);
				list.add(action);
			}
		} catch (SQLException e) {
			throw new RuntimeException();
		}
		return list;
	}

	@Override
	public List<WebMenu> getUserMenus(String userId) {
		DataQuery query = DataQuery
				.getInstance(
						1,
						"SORT,ID,PARENTID,NAME,TYPE,STATE,ICON,IMGID,PARAMS,AUTHKEY",
						"(SELECT c.SORT,c.ID,c.PARENTID,c.NAME,c.TYPE,c.STATE,c.ICON,c.IMGID,c.PARAMS,d.AUTHKEY FROM  alone_auth_userorgpost a LEFT JOIN alone_auth_postaction b ON a.POSTID =b.POSTID LEFT JOIN alone_auth_actiontree c ON b.MENUID=c.ID LEFT JOIN alone_auth_action d ON d.ID=c.ACTIONID WHERE (d.STATE = '1'||d.STATE IS NULL) and a.userid='"
								+ userId
								+ "' order by LENGTH(c.TREECODE),c.SORT asc) e");
		List<WebMenu> menus = new ArrayList<WebMenu>();
		query.setPagesize(1000);
		query.setNoCount();
		try {
			for (Map<String, Object> map : query.search().getResultList()) {
				AuthMenuImpl node = new AuthMenuImpl();
				node.setIcon(map.get("ICON") != null ? map.get("ICON")
						.toString() : null);
				node.setId(map.get("ID") != null ? map.get("ID").toString()
						: null);
				node.setName(map.get("NAME") != null ? map.get("NAME")
						.toString() : null);
				node.setParams(map.get("PARAMS") != null ? map.get("PARAMS")
						.toString() : null);
				node.setParentid(map.get("PARENTID") != null ? map.get(
						"PARENTID").toString() : null);
				node.setUrl(map.get("AUTHKEY") != null ? map.get("AUTHKEY")
						.toString() : null);
				menus.add(node);
			}
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
		return menus;
	}

	@Override
	public List<Post> getUserPosts(String userId) {
		List<Userpost> userposts = userpostDao.selectEntitys(DBRule.addRule(
				"USERID", userId, "="));
		List<Post> list = new ArrayList<Post>();
		for (Userpost userPost : userposts) {
			list.add(postDao.getEntity(userPost.getPostid()));
		}
		return list;
	}

	@Override
	public boolean editLoginPassword(String loginname, String oldPassword,
			String newPassword) {
		User user = getUserByLoginName(loginname);
		if (user == null) {
			throw new RuntimeException("不存在该用户!");
		}
		if (authUtil.encodeLoginPasswordOnMd5(oldPassword, loginname).equals(
				user.getPassword())) {
			// 验证成功,修改密码
			user.setPassword(authUtil.encodeLoginPasswordOnMd5(newPassword,
					loginname));
			userDao.editEntity(user);
			return true;
		} else {
			throw new RuntimeException("原密码错误!");
		}
	}

	@Override
	public List<String> getUserPostIds(String userId) {
		List<Userpost> userposts = userpostDao.selectEntitys(DBRule.addRule(
				"USERID", userId, "="));
		List<String> list = new ArrayList<String>();
		for (Userpost userPost : userposts) {
			list.add(userPost.getPostid());
		}
		return list;
	}

	@Override
	public Organization getUserOrganization(String userId) {
		List<Post> posts = getUserPosts(userId);
		for (Post post : posts) {
			if (post.getType().equals("1")) {
				return organizationDao.getEntity(post.getOrganizationid());
			}
		}
		return null;
	}
}
